package com.apache.passport.common;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URL;
import java.util.Date;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;

import org.apache.commons.httpclient.NameValuePair;
import org.dom4j.Document;
import org.dom4j.io.SAXReader;

/**
 * 
 * <p>@Description http请求帮助类
 * <p>@Copyright(c)2013:
 * <p>@Author: lvcai
 * <p>@Create Date 2013-7-29 下午03:54:28
 * <p>@Modified By:lvcai
 * <p>@Modified Date:2013-7-29 下午03:54:28
 * <p>@version v1.0
 */
public class PostHttps {

	/**
	 * 公共方法
	 * post http 请求，接受返回的结果xml文档	 
	 * @param url webservice地址
	 * @param parasInput 传递的参数
	 * @return xml类型字符串
	 */
	public static String postHttps(String httpsurl, NameValuePair[] parasInput) {
		StringBuilder sb = new StringBuilder();
		try {
			SSLSocketFactory ssf = getSSLSocketFactory();
			URL url = new URL(httpsurl);
			HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();
			httpUrlConn.setSSLSocketFactory(ssf);

			httpUrlConn.setDoOutput(true);
			httpUrlConn.setDoInput(true);
			httpUrlConn.setUseCaches(false);

			// 设置请求方式（GET/POST）
			httpUrlConn.setRequestMethod("POST");
			String outputStr = getHttpsUrl(parasInput);
			// 当有数据需要提交时
			if (null != outputStr) {
				OutputStream outputStream = httpUrlConn.getOutputStream();
				// 注意编码格式，防止中文乱码
				outputStream.write(outputStr.getBytes("UTF-8"));
				outputStream.close();
			}
			// 将返回的输入流转换成字符串
			InputStream inputStream = httpUrlConn.getInputStream();
			int code = httpUrlConn.getResponseCode();
			if (HttpsURLConnection.HTTP_OK == code) { //如果执行成功
				InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
				BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
				String line = null;
				try {
					while ((line = bufferedReader.readLine()) != null) {
						sb.append(line + "\n");
					}
				} catch (IOException e) {
					e.printStackTrace();
				} finally {
					try {
						inputStream.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
				inputStream.close();
			} else {
				System.out.println("HTTP请求响应失败，错误码为:[" + code + "]");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return sb.toString();
	}

	/**
	 * 公共方法
	 * post http 请求，接受返回的结果xml文档	 
	 * @param url webservice地址
	 * @param parasInput 传递的参数
	 * @return Document 对象
	 */
	public static Document postHttpsDocument(String httpsurl, NameValuePair[] parasInput) {
		Document doc = null;
		try {
			SSLSocketFactory ssf = getSSLSocketFactory();
			URL url = new URL(httpsurl);
			HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();
			httpUrlConn.setSSLSocketFactory(ssf);

			httpUrlConn.setDoOutput(true);
			httpUrlConn.setDoInput(true);
			httpUrlConn.setUseCaches(false);
			// 设置请求方式（GET/POST）
			httpUrlConn.setRequestMethod("POST");
			String outputStr = getHttpsUrl(parasInput);
			// 当有数据需要提交时
			if (null != outputStr) {
				OutputStream outputStream = httpUrlConn.getOutputStream();
				// 注意编码格式，防止中文乱码
				outputStream.write(outputStr.getBytes("UTF-8"));
				outputStream.close();
			}
			// 将返回的输入流转换成字符串
			InputStream inputStream = httpUrlConn.getInputStream();
			int code = httpUrlConn.getResponseCode();
			if (HttpsURLConnection.HTTP_OK == code) { //如果执行成功
				InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
				doc = (new SAXReader()).read(inputStreamReader);
				inputStream.close();
			} else {
				System.out.println("HTTP请求响应失败，错误码为:[" + code + "]");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return doc;
	}

	private static SSLSocketFactory getSSLSocketFactory() throws Exception {
		// 创建SSLContext对象，并使用我们指定的信任管理器初始化
		TrustManager[] tm = { new MyX509TrustManager() };
		SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
		sslContext.init(null, tm, new java.security.SecureRandom());
		// 从上述SSLContext对象中得到SSLSocketFactory对象
		SSLSocketFactory ssf = sslContext.getSocketFactory();
		return ssf;
	}

	private static String getHttpsUrl(NameValuePair[] parasInput) {
		StringBuffer buffer = new StringBuffer();
		int count = 0;
		if (null != parasInput) {
			count = parasInput.length;
			for (int i = 0; i < count; i++) {
				if (i == 0)
					buffer.append(parasInput[i].getName() + "=" + parasInput[i].getValue());
				else
					buffer.append("&" + parasInput[i].getName() + "=" + parasInput[i].getValue());
			}
		}
		if (count > 0)
			buffer.append("&");
		buffer.append("httpRand=" + "" + new Date().getTime());
		return buffer.toString();
	}

	/**
	 * 
	 * @param url
	 * @param parasInput
	 * @return
	 */
	public static String postHttpsString(String httpsurl, NameValuePair[] parasInput) {
		String value = "";
		try {
			SSLSocketFactory ssf = getSSLSocketFactory();
			URL url = new URL(httpsurl);
			HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();
			httpUrlConn.setSSLSocketFactory(ssf);

			httpUrlConn.setDoOutput(true);
			httpUrlConn.setDoInput(true);
			httpUrlConn.setUseCaches(false);

			// 设置请求方式（GET/POST）
			httpUrlConn.setRequestMethod("POST");
			String outputStr = getHttpsUrl(parasInput);
			// 当有数据需要提交时
			if (null != outputStr) {
				OutputStream outputStream = httpUrlConn.getOutputStream();
				// 注意编码格式，防止中文乱码
				outputStream.write(outputStr.getBytes("UTF-8"));
				outputStream.close();
			}
			// 将返回的输入流转换成字符串
			InputStream inputStream = httpUrlConn.getInputStream();
			int code = httpUrlConn.getResponseCode();
			if (HttpsURLConnection.HTTP_OK == code) { //如果执行成功
				byte[] temp = new byte[1024];
				byte[] tmp = new byte[1024 * 4];
				int t1 = 0;
				int t2 = 0;
				while ((t2 = inputStream.read(temp)) != -1) {
					System.arraycopy(temp, 0, tmp, t1, t2);
					t1 = t1 + t2;
				}
				value = new String(tmp, "UTF-8");
				value = value.trim();
				inputStream.close();
			} else {
				System.out.println("HTTP请求响应失败，错误码为:[" + code + "]");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return value;
	}

}